package com.imooc.zuul.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.imooc.zuul.exception.RateLimitException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

/** 限流
 * @author : 浦希成
 * @date : 2018/8/2 9:08
 */
@Component
public class RateLimitFilter extends ZuulFilter {
    //每秒放多少令牌
    private static final RateLimiter RATE_LIMITER=RateLimiter.create(100);
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return SERVLET_DETECTION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();
        if(!RATE_LIMITER.tryAcquire()){
            // 没有拿到令牌
            throw new RateLimitException();
        }
        return null;
    }
}
